import axios from 'axios'

class ProxyJSON {
  constructor(payload) {
    const { baseURL, timeout } = payload
    this._timeout = timeout
    this._baseURL = baseURL

    this._service = this._get_service()
  }

  _get_service() {
    const service = axios.create({
      baseURL: this._baseURL,
      timeout: this._timeout
    })

    service.interceptors.request.use(
      config => {
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )

    service.interceptors.response.use(
      response => {
        const res = response.data
        return res
      },
      error => {
        return Promise.reject(error)
      }
    )

    return service
  }

  async call(url, payload = {}) {
    const url2 = url[0] === '/' ? url : `/${url}`
    const data = {
      jsonrpc: '2.0',
      method: 'call',
      params: payload,
      id: Math.floor(Math.random() * 1000000000 + 1)
    }

    const response = await this._service({
      url: url2,
      method: 'post',
      data
    })

    return response
  }
}

export class JsonRequest {
  constructor() {}

  static get baseURL() {
    return this._baseURL
  }

  static set baseURL(val) {
    this._baseURL = val
  }

  static get timeout() {
    return this._timeout
  }

  static set timeout(val) {
    this._timeout = val
  }

  static init({ baseURL, timeout }) {
    this.baseURL = baseURL
    this.timeout = timeout
  }

  static async json_call(url, payload = {}) {
    const req = new ProxyJSON({
      baseURL: this.baseURL,
      timeout: this.timeout
    })

    const data = await req.call(url, payload)
    const { error, result } = data

    if (error) {
      throw error
    } else {
      return result
    }
  }
}

JsonRequest._baseURL = undefined
JsonRequest._timeout = undefined
